package com.artqiyi.dollmachine.views.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;


import com.artqiyi.dollmachine.R;
import com.artqiyi.dollmachine.common.Base.BaseActivity;
import com.artqiyi.dollmachine.common.constant.Constant;
import com.artqiyi.dollmachine.common.constant.UserConfigConstant;
import com.artqiyi.dollmachine.presenter.base.BasePresenter;
import com.artqiyi.dollmachine.utils.manager.ConfigManager;
import com.artqiyi.dollmachine.utils.manager.UserInfoManager;
import com.artqiyi.dollmachine.views.widget.ToolBarView;

import butterknife.Bind;
import timber.log.Timber;

/**
 * Created by Administrator on 2017/11/9 0009.
 */

public class WebViewActivity extends BaseActivity {

    @Bind(R.id.progressBar)
    ProgressBar progressBar;
    @Bind(R.id.webView)
    WebView webView;

    private String mWebViewType;

    private ToolBarView mToolBarView;
    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    protected void handleIntent(Intent intent) {
        super.handleIntent(intent);
        mWebViewType = getIntent().getStringExtra(Constant.KEY_MINE_WEBVIEW_TYPE);
    }

    @Override
    protected void handleToolBar(ToolBarView toolBar) {
        super.handleToolBar(toolBar);
        mToolBarView = toolBar;
        toolBar.setTitleText(getWebViewTitle());
        toolBar.setOnLeftClickListener(new ToolBarView.OnBarLeftClickListener() {
            @Override
            public void onLeftClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();
                }else {
                    finish();
                }
            }
        });
    }

    private String getWebViewTitle() {
        String titleStr = null;
        if (TextUtils.equals(mWebViewType, Constant.MINE_ORDER)) {
            titleStr = "订单管理";
        } else if (TextUtils.equals(mWebViewType, Constant.MINE_ADDRESS)) {
            titleStr = "收货地址";
        } else if (TextUtils.equals(mWebViewType, Constant.MINE_MYWAWA)) {
            titleStr = "我的娃娃";
        }
        return titleStr;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        progressBar.setMax(100);//设置加载进度最大值
        WebSettings webSettings = webView.getSettings();
//        if (Build.VERSION.SDK_INT >= 19) {
//            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//加载缓存否则网络
//        }

        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);//图片自动缩放 打开
        } else {
            webSettings.setLoadsImagesAutomatically(false);//图片自动缩放 关闭
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//软件解码
        }
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);//硬件解码

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webSettings.setSupportZoom(true);// 设置可以支持缩放
        webSettings.setBuiltInZoomControls(true);// 设置出现缩放工具 是否使用WebView内置的缩放组件，由浮动在窗口上的缩放控制和手势缩放控制组成，默认false

        webSettings.setDisplayZoomControls(false);//隐藏缩放工具
        webSettings.setUseWideViewPort(true);// 扩大比例的缩放

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        webSettings.setLoadWithOverviewMode(true);

//        webSettings.setDatabaseEnabled(true);//
//        webSettings.setSavePassword(true);//保存密码
//        webSettings.setDomStorageEnabled(true);//是否开启本地DOM存储  鉴于它的安全特性（任何人都能读取到它，尽管有相应的限制，将敏感数据存储在这里依然不是明智之举），Android 默认是关闭该功能的。
//        webView.setSaveEnabled(true);
//        webView.setKeepScreenOn(true);

        // 设置setWebChromeClient对象
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                //设置标题
                Timber.d("webviewactivity_title:" + title);
                mToolBarView.setTitleText(title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                if (progressBar != null) {
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        //设置此方法可在WebView中打开链接，反之用浏览器打开
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (webView != null && !webView.getSettings().getLoadsImagesAutomatically()) {
                    webView.getSettings().setLoadsImagesAutomatically(true);
                }
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);
                }
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                }

                // Otherwise allow the OS to handle things like tel, mailto, etc.
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });
        webView.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String paramAnonymousString1, String paramAnonymousString2, String paramAnonymousString3, String paramAnonymousString4, long paramAnonymousLong) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setData(Uri.parse(paramAnonymousString1));
                startActivity(intent);
            }
        });

    }

    @Override
    public void reLoadData() {
        super.reLoadData();
        String url = ConfigManager.getInstance().getConfigBean().getMall_url() + getWebViewUrl() + UserConfigConstant.getToken();
//        String url = ConfigManager.getInstance().getMallUrl() + getWebViewUrl() + UserInfoManager.getInstance().getUserInfoBean().getApi_token();
        Timber.d("url:" + url);
        webView.loadUrl(url);
    }

    private String getWebViewUrl() {
        String urlStr = null;
        if (TextUtils.equals(mWebViewType, Constant.MINE_ORDER)) {
            urlStr = Constant.URL_MINE_ORDER;
        } else if (TextUtils.equals(mWebViewType, Constant.MINE_ADDRESS)) {
            urlStr = Constant.URL_MINE_ADDRESS;
        } else if (TextUtils.equals(mWebViewType, Constant.MINE_MYWAWA)) {
            urlStr = Constant.URL_MINE_MYWAWA;
        }
        return urlStr;
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void onPause() {
        try {
            webView.getClass().getMethod("onPause").invoke(webView, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        try {
            webView.getClass().getMethod("onResume").invoke(webView, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        }else {
            finish();
        }
    }
}
